﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Entity;
using System.IO;

public partial class Pages_Cart : System.Web.UI.Page
{
    static Label lblTotal;
    public bool CheckCredit
    {
        get
        {
            bool editMode = false;
            if (ViewState["editMode"] != null)
                editMode = (bool)ViewState["editMode"];
            return editMode;
        }
        set
        {
            ViewState["editMode"] = value;
        }
    } 
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {

            if (Session["loginClient"] != null)
            {
                Customer cus = (Customer)Session["loginClient"];

                if (cus.C_Status)
                {
                    lblTotal = new Label();
                    BindDataTo();
                    for (int i = 1; i <= 12; i++)
                    {
                        cbxMonth.Items.Add(i.ToString());
                    }

                    for (int i = int.Parse(DateTime.Now.Year.ToString()) + 20; i >= 1970; i--)
                    {
                        cbxYear.Items.Add(i.ToString());
                    }

                    BindInfo();
                }
                else
                {
                    Response.Redirect("../Pages/AccountLock.aspx");
                }
            }
            else
            {
                Response.Redirect("../Pages/Login.aspx");
            }
        }
        if (radDirectPay.Checked)
        {
            tableCredit.Visible = false;
        }
        else if (radCreditCart.Checked)
        {
            tableCredit.Visible = true;
        }
    }

    private void BindInfo()
    {
        Customer cus = (Customer)Session["loginClient"];
        txtName.Text = cus.F_Name + " " + cus.L_Name;
        txtPhone.Text = cus.P_No;
        txtAddress.Text = cus.Address;
    }

    private void BindDataTo()
    {
        if (Session["Cart"] == null)
        {
            lblError.Visible = true;
            //lblTotal.Text = "0 VND";
            //lblTotal.Text = "0 VND";
        }
        else
        {
            lblError.Visible = false;
            Hashtable htb = (Hashtable)Session["Cart"];
            double t = 0.0d;
            if (htb.Count <= 0)
            {
                lblTotal.Text = 0 + "";
            }
            else
            {
                foreach (Product item in htb.Values)
                {
                    t += item.Total;
                }
                lblTotal.Text = t + "";
            }
            gvCart.DataSource = htb.Values;
            gvCart.DataBind();
        }
    }

    protected void lnkDelete_Click(object sender, EventArgs e)
    {
        LinkButton lnk = (LinkButton)sender;
        string ca = lnk.CommandArgument;
        string[] splitCa = ca.Split(',');
        int sizeid = int.Parse(splitCa[0].ToString());
        int imageid = int.Parse(splitCa[1].ToString());

        Hashtable htb = (Hashtable)Session["Cart"];
        Hashtable temp = new Hashtable();
        foreach (KeyProduct item in htb.Keys)
        {
            temp.Add(item, htb[item]);
        }

        foreach (KeyProduct item in temp.Keys)
        {
            if (item.Image_id == imageid && item.Size_id == sizeid)
            {
                htb.Remove(item);
            }
        }
        Session["Cart"] = htb;
        BindDataTo();
    }

    protected void gvCart_RowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Footer)
        {
            GridView gvFooter = (GridView)sender;
            GridViewRow gvRow = new GridViewRow(gvCart.Rows.Count, 0, DataControlRowType.Footer, DataControlRowState.Insert);
            TableCell tableCell = new TableCell();
            Label lblTitle = new Label();
            lblTitle.Text = "Total All:";
            Label lblEmpty = new Label();
            lblEmpty.Text = "";
            MergeColumn(gvRow, tableCell, 5, lblTitle, HorizontalAlign.Right);
            MergeColumn(gvRow, tableCell, 1, lblTotal, HorizontalAlign.Center);
            MergeColumn(gvRow, tableCell, 1, lblEmpty, HorizontalAlign.Right);
            gvFooter.Controls[0].Controls.AddAt(gvCart.Rows.Count + 1, gvRow);
        }
    }

    protected static void MergeColumn(GridViewRow gvRow, TableCell tbCell, int colSpan, Label txt, HorizontalAlign ha)
    {
        tbCell = new TableCell();
        tbCell.Text = txt.Text;
        tbCell.ColumnSpan = colSpan;
        tbCell.HorizontalAlign = ha;
        gvRow.Cells.Add(tbCell);
    }

    protected void btnChange_Click(object sender, EventArgs e)
    {
        
        if (gvCart.Rows.Count > 0 && gvCart.Rows != null)
        {

            ImagesUI image = new ImagesUI();
            SizeUI size = new SizeUI();
            Hashtable htb = new Hashtable();
            for (int i = 0; i < gvCart.Rows.Count; i++)
            {
                int imageid = int.Parse(gvCart.Rows[i].Cells[0].Text);              
                DataSet dsImage = new DataSet();
                dsImage = image.Get(imageid);
                DropDownList drl = (DropDownList)gvCart.Rows[i].FindControl("cbxSize");
                int sizeid = int.Parse(drl.SelectedValue.ToString());
                DataSet dsSize = new DataSet();
                dsSize = size.Get(sizeid);
                float price = float.Parse(dsSize.Tables[0].Rows[0]["Price"].ToString());
                TextBox txtQ = (TextBox)gvCart.Rows[i].FindControl("txtQuantity");
                int quantity = Convert.ToInt32(txtQ.Text);
                string imageurl = dsImage.Tables[0].Rows[0]["I_URL"].ToString();
                string imagename = dsImage.Tables[0].Rows[0]["I_Name"].ToString();

                KeyProduct key = new KeyProduct(sizeid, imageid);
                if (htb == null)
                {
                    htb.Add(key, new Product(sizeid, imagename, imageurl, imageid, price, quantity, quantity * price));
                }
                else
                {
                    bool b = false;
                    Product te = null;
                    foreach (KeyProduct item in htb.Keys)
                    {
                        if (item.Size_id == sizeid && item.Image_id == imageid)
                        {
                            b = true;
                            te = (Product)htb[item];
                        }
                    }

                    if (b)
                    {
                        Product p = te;
                        p.Quantity += quantity;
                        p.Total += quantity * price;
                    }
                    else
                    {
                        htb.Add(key, new Product(sizeid, imagename, imageurl, imageid, price, quantity, quantity * price));
                    }
                }
                
            }

            Session["Cart"] = htb;
            BindDataTo();
        }
        else
        {
            Response.Write("<script>alert('Data is Empty');</script>");
        }
    }
    protected void btnOrder_Click(object sender, EventArgs e)
    {
        if (Session["loginClient"] != null)
        {
            Customer cus = (Customer)Session["loginClient"];
                if (Session["Cart"] != null)
                {
                    if (radDirectPay.Checked)
                    {
                        try
                        {
                            Hashtable htb = (Hashtable)Session["Cart"];
                            OrderBillUI orderUI = new OrderBillUI();
                            orderUI.Add(DateTime.Now, txtAddress.Text, txtPhone.Text, txtName.Text, 0, 1, cus.Cusid);
                            DataSet ds = orderUI.GetNewOrder();
                            int oid = Convert.ToInt32(ds.Tables[0].Rows[0]["O_ID"].ToString());
                            string folder = "folder_" + oid;
                            orderUI.UpdateFolder(oid, folder);
                            string pathFolder = Server.MapPath("~/Upload/orderbill/" + folder);
                            if (!Directory.Exists(pathFolder))
                            {
                                Directory.CreateDirectory(pathFolder);
                            }
                            OrderDetailUI orderDetailUI = new OrderDetailUI();

                            foreach (Product item in htb.Values)
                            {
                                Product p = item;
                                string pathFileSource = Server.MapPath("~/" + p.Image_URL);
                                string pathFileDes = pathFolder + "/" + p.ImageName;
                                orderDetailUI.Add(oid, p.Image_id, p.Size_id, p.Price, p.Quantity);
                                if (!File.Exists(pathFileDes))
                                {
                                    File.Copy(pathFileSource, pathFileDes);
                                }
                            }
                            Response.Write("<script>alert('Order successful'); window.location='../Pages/Home.aspx';</script>");
                            Session["Cart"] = null;
                        }
                        catch (Exception ex)
                        {
                            Response.Write("<script>alert('Order fail');</script>");
                        }

                    }
                    else if (radCreditCart.Checked)
                    {
                        if (CheckCredit)
                        {
                            try
                            {
                                Hashtable htb = (Hashtable)Session["Cart"];
                                OrderBillUI orderUI = new OrderBillUI();
                                orderUI.Add(DateTime.Now, txtAddress.Text, txtPhone.Text, txtName.Text, 1, 2, cus.Cusid);
                                DataSet ds = orderUI.GetNewOrder();
                                int oid = Convert.ToInt32(ds.Tables[0].Rows[0]["O_ID"].ToString());
                                string folder = "folder_" + oid;
                                orderUI.UpdateFolder(oid, folder);
                                string pathFolder = Server.MapPath("~/Upload/orderbill/" + folder);
                                if (!Directory.Exists(pathFolder))
                                {
                                    Directory.CreateDirectory(pathFolder);
                                }
                                OrderDetailUI orderDetailUI = new OrderDetailUI();

                                foreach (Product item in htb.Values)
                                {
                                    Product p = item;
                                    string pathFileSource = Server.MapPath("~/" + p.Image_URL);
                                    string pathFileDes = pathFolder + "/" + p.ImageName;
                                    orderDetailUI.Add(oid, p.Image_id, p.Size_id, p.Price, p.Quantity);
                                    if (!File.Exists(pathFileDes))
                                    {
                                        File.Copy(pathFileSource, pathFileDes);
                                    }
                                }
                                Response.Write("<script>alert('Order successful'); window.location='../Pages/Home.aspx';</script>");
                                Session["Cart"] = null;
                            }
                            catch (Exception ex)
                            {
                                Response.Write("<script>alert('Order fail');</script>");
                            }
                        }
                        else
                        {
                            Response.Write("<script>alert('Invalid credit card information or you dont click in check credit card button');</script>");
                        }
                    }
                }
                else
                {
                    Response.Write("<script>alert('Your Cart is empty');</script>");
                }
        }
        else
        {
            Response.Redirect("../Pages/Login.aspx");
        }
    }
    protected void btnCheckCreditCard_Click(object sender, EventArgs e)
    {
        if (txtCardNumber.Text != "")
        {
            localhost.Service sv = new localhost.Service();
            string strEncrypt = sv.EncyptCredit(txtCardNumber.Text.Trim());
            if (sv.CheckCard(strEncrypt))
            {
                Response.Write("<script>alert('Valid  credit card information');</script>");
                CheckCredit = true;
            }
            else
            {
                Response.Write("<script>alert('Invalid  credit card information');</script>");
                CheckCredit = false;
            }
        }
    }

    protected void btnReset_Click(object sender, EventArgs e)
    {
        Response.Redirect("../Pages/Cart.aspx");
    }
    protected void btnContinue_Click(object sender, EventArgs e)
    {
        Response.Redirect("../Pages/MyAlbum.aspx");
    }
}
